/**
 * Copyright (c) 2018 湖南牛数 All rights reserved.
 * <p>
 * https://www.dshubs.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.dshubs.service.impl;

import cn.hutool.core.collection.CollUtil;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.dao.SysRoleMenuDao;
import io.dshubs.entity.SysRoleMenuEntity;
import io.dshubs.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色菜单关系
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
@Service
public class SysRoleMenuServiceImpl extends BaseServiceImpl<SysRoleMenuDao, SysRoleMenuEntity> implements SysRoleMenuService {

    @Override
    public List<Long> getMenuIdList(Long roleId) {
        return baseDao.getMenuIdList(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        //先删除角色菜单关系
        deleteByRoleIds(new Long[]{roleId});

        //角色没有一个菜单权限的情况
        if (CollUtil.isEmpty(menuIdList)) {
            return;
        }

        //保存角色菜单关系
        for (Long menuId : menuIdList) {
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);

            //保存
            insert(sysRoleMenuEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByRoleIds(Long[] roleIds) {
        baseDao.deleteByRoleIds(roleIds);
    }

    /**
     * 根据角色id和菜单id，删除角色菜单关系
     *
     * @param roleIds 角色ids
     * @param menuId  菜单id
     */
    @Override
    public void deleteByRoleIdsAndMenuId(Long[] roleIds, Long menuId) {
        baseDao.deleteByRoleIdsAndMenuId(roleIds, menuId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByMenuId(Long menuId) {
        baseDao.deleteByMenuId(menuId);
    }

    /**
     * 保存或修改（适用于单条的）
     *
     * @param roleIdList 角色ID
     * @param menuId     菜单ID
     */
    @Override
    public void saveOrUpdate(List<Long> roleIdList, Long menuId) {
        //先删除角色菜单关系
        this.deleteByRoleIdsAndMenuId(roleIdList.toArray(new Long[0]), menuId);

        //角色没有一个菜单权限的情况
        if (menuId == null) {
            return;
        }
        for (Long roleId : roleIdList) {
            //保存角色菜单关系
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);
            //保存
            insert(sysRoleMenuEntity);
        }
    }

}